package com.siyu.preplan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyu.basedata.iothlpoint.domain.IotHLPoint;
import com.siyu.basedata.iothlpoint.service.IIotHLPointService;
import com.siyu.basedata.plan.domain.Plan;
import com.siyu.basedata.plan.service.IPlanService;
import com.siyu.common.config.minio.MinIOConfigProperties;
import com.siyu.common.constant.MinioOrOssConstants;
import com.siyu.common.core.domain.AjaxResult;
import com.siyu.common.utils.aliyun.service.FileOssStorageService;
import com.siyu.common.utils.minio.service.FileStorageService;
import com.siyu.common.utils.uuid.IdUtils;
import com.siyu.preplan.dto.PlanPDepotDto;
import com.siyu.preplan.dto.PlanPDtmlDto;
import com.siyu.preplan.planpcondition.domain.PlanPCondition;
import com.siyu.preplan.planpcondition.service.impl.PlanPConditionServiceImpl;
import com.siyu.preplan.planpdepot.domain.PlanPDepot;
import com.siyu.preplan.planpdepot.service.IPlanPDepotService;
import com.siyu.preplan.planpdocument.service.impl.PlanPDocumentServiceImpl;
import com.siyu.preplan.planpdtml.domain.PlanPDtml;
import com.siyu.preplan.planpdtml.service.IPlanPDtmlService;
import com.siyu.preplan.planpfbase.domain.PlanPFbase;
import com.siyu.preplan.planpfbase.service.IPlanPFbaseService;
import com.siyu.preplan.planpmaterial.domain.PlanPMaterial;
import com.siyu.preplan.planpmaterial.service.impl.PlanPMaterialServiceImpl;
import com.siyu.preplan.planpplan.domain.PlanPPlan;
import com.siyu.preplan.planpplan.service.impl.PlanPPlanServiceImpl;
import com.siyu.preplan.service.PlanPeService;
import com.siyu.preplan.vo.*;
import com.siyu.rehearsal.previewpfbase.domain.PreviewPFbase;
import com.siyu.rehearsal.previewpfbase.mapper.PreviewPFbaseMapper;
import com.siyu.rehearsal.previewpfbase.service.IPreviewPFbaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PlanPeServiceImpl implements PlanPeService {

    private static Boolean minioOrOss = MinioOrOssConstants.getMinioOrOss();

    @Autowired
    private IPlanService planService;

    @Autowired
    private PlanPMaterialServiceImpl planPMaterialService;

    @Autowired
    private PlanPDocumentServiceImpl planPDocumentService;

    @Autowired
    private PlanPConditionServiceImpl planPConditionService;

    @Autowired
    private PlanPPlanServiceImpl planPPlanService;

    @Autowired
    private IIotHLPointService iIotHLPointService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    @Autowired
    private FileOssStorageService fileOssStorageService;

    @Autowired
    private IPlanPFbaseService planPFbaseService;

    @Autowired
    private IPreviewPFbaseService previewPFbaseService;

    @Autowired
    private PreviewPFbaseMapper previewPFbaseMapper;

    @Autowired
    private IPlanPDtmlService planPDtmlService;

    @Autowired
    private IPlanPDepotService planPDepotService;


    @Override
    public PlanPPlanVo getPlanPPlanVos(String id, Integer planLevel) {
        //根据预案id进行预案详情查询
        QueryWrapper<PlanPPlan> planPPlanQueryWrapper = new QueryWrapper<>();
        planPPlanQueryWrapper.select("id", "plan_level", "organization_unit", "transfer_object", "transfer_route", "resettlement_site", "safe", "danger", "aftercare", "route", "matter")
                .eq("plan_id", id)
                .eq("plan_level", planLevel);
        PlanPPlan planPPlan = planPPlanService.getOne(planPPlanQueryWrapper);

        if (planPPlan == null) {
            return null;
        }

        // 查询阈值条件
        QueryWrapper<PlanPCondition> planPConditionQueryWrapper = new QueryWrapper<>();
        planPConditionQueryWrapper.select("back_time", "rainfall", "condition", "sequence_number,tap")
                .eq("plan_id", planPPlan.getId())
                .orderByAsc("sequence_number");
        List<PlanPCondition> planPConditions = planPConditionService.list(planPConditionQueryWrapper);

        PlanPPlanVo planPPlanVo = new PlanPPlanVo();
        BeanUtil.copyProperties(planPPlan, planPPlanVo);
        planPPlanVo.setTriggerConditions(planPConditions);
        return planPPlanVo;
    }

    @Override
    public PlanPMaterialVo getPlanPMaterialVo(String id, Integer planLevel) {

        Plan plan = planService.getById(id);
        //根据预案id查询预案救灾物资信息
        QueryWrapper<PlanPMaterial> planPMaterialQueryWrapper = new QueryWrapper<>();
        planPMaterialQueryWrapper.select("rescue_tools", "basic_materials", "set_lights", "correspondence", "first_aid", "transport")
                .eq("rscd", plan.getRscd());
        PlanPMaterial planPMaterial = planPMaterialService.getOne(planPMaterialQueryWrapper);

        PlanPMaterialVo planPMaterialVo = new PlanPMaterialVo();
        //复制PlanPMaterial对象到PlanPMaterialVo对象进行输出
        BeanUtil.copyProperties(planPMaterial, planPMaterialVo);
        return planPMaterialVo;
    }

    @Override
    public PlanSummaryVo getPlanSummaryVo(String rscd) {
     /*   // 查询水文站数量
        QueryWrapper<IotHLPoint> iotHLPointQueryWrapper = new QueryWrapper<>();
        iotHLPointQueryWrapper.eq("rscd", rscd)
                .eq("sttp", "2");
        int bs = iIotHLPointService.count(iotHLPointQueryWrapper);

        // 查询雨量站数量
        QueryWrapper<IotHLPoint> rsiotHLPointQueryWrapper = new QueryWrapper<>();
        rsiotHLPointQueryWrapper.eq("rscd", rscd)
                .eq("sttp", "3");
        int rs = iIotHLPointService.count(rsiotHLPointQueryWrapper);*/

        QueryWrapper<PreviewPFbase> previewPFbaseQueryWrapper = new QueryWrapper<>();
        previewPFbaseQueryWrapper
                .eq("rscd", rscd);
        List<PreviewPFbase> previewPFbases = previewPFbaseService.list(previewPFbaseQueryWrapper);

        Integer fzTarget = previewPFbases.stream()
                .mapToInt(PreviewPFbase::getIPpl)
                .sum();
        Integer dz = previewPFbaseMapper.countDistinct(rscd);

        return PlanSummaryVo.builder()
                .dz(dz)
                .fzTarget(fzTarget)
                .fzVillage(previewPFbases.size())
                .build();
    }

    @Override
    public AjaxResult getView(String id, Integer planLevel) {
        //根据预案id和响应预案等级查询预案地图编辑信息
        PlanPViewVo planPViewVo = null;
        try {
            Plan plan = planService.getById(id);

            QueryWrapper<PlanPPlan> planPPlanQueryWrapper = new QueryWrapper<>();
            planPPlanQueryWrapper.select("id", "safe", "danger", "aftercare", "route", "matter")
                    .eq("plan_id", id)
                    .eq("plan_level", planLevel);
            PlanPPlan planPPlan = planPPlanService.getOne(planPPlanQueryWrapper);
            if (planPPlan == null) {
                return AjaxResult.warn("查无数据!");
            }

            //查询村镇基础信息
            QueryWrapper<PlanPFbase> planPFbaseQueryWrapper = new QueryWrapper<>();
            planPFbaseQueryWrapper.eq("plan_id", planPPlan.getId());
            PlanPFbase planPFbase = planPFbaseService.getOne(planPFbaseQueryWrapper);

            planPViewVo = new PlanPViewVo();
            BeanUtil.copyProperties(planPPlan, planPViewVo);
            if (planPFbase != null) {
                planPViewVo.setV_name(planPFbase.getVName());
                planPViewVo.setIArea(planPFbase.getIArea());
                if (planPFbase.getIPpl() != null) {
                    planPViewVo.setIPopulace(planPFbase.getIPpl() / 10000.0);
                }
                planPViewVo.setAal(planPFbase.getIPg());
                planPViewVo.setAh(planPFbase.getIH());
            }

            // 仓库位置信息
            QueryWrapper<PlanPDepot> planPDepotQueryWrapper = new QueryWrapper<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String datayear = sdf.format(new Date());
            planPDepotQueryWrapper.select("id","depot_name","x","y")
                    .eq("rscd", plan.getRscd());
            List<PlanPDepot> planPDepots = planPDepotService.list(planPDepotQueryWrapper);
            planPViewVo.setPlanPDepots(planPDepots);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("数据查询失败!");
        }
        return AjaxResult.success(planPViewVo);
    }

    @Override
    @Transactional
    public void delete(List<String> ids) throws MalformedURLException {
        for (String id : ids) {
            //删除预案
            planService.deletePlanById(id);
            //删除预案相关物资
/*        QueryWrapper<PlanPMaterial> planPMaterialQueryWrapper = new QueryWrapper<>();
        planPMaterialQueryWrapper.eq("plan_id", id);
        planPMaterialService.remove(planPMaterialQueryWrapper);*/


            //删除预案详情
            QueryWrapper<PlanPPlan> planPPlanQueryWrapper = new QueryWrapper<>();
            planPPlanQueryWrapper.eq("plan_id", id);
            // 查询 阈值条件id
            List<PlanPPlan> planPPlans = planPPlanService.list(planPPlanQueryWrapper);

            planPPlanService.remove(planPPlanQueryWrapper);


            //删除预案相关触发条件
            //删除minio上的预案文件
            ArrayList<String> urls = new ArrayList<>();
            for (int i = 0; i < planPPlans.size(); i++) {
                PlanPPlan planPPlan = planPPlans.get(i);
                if (planPPlan.getSafe() != null) {
                    urls.add(planPPlan.getSafe());
                }
                if (planPPlan.getAftercare() != null) {
                    urls.add(planPPlan.getAftercare());
                }
                if (planPPlan.getDanger() != null) {
                    urls.add(planPPlan.getDanger());
                }
                if (planPPlan.getRoute() != null) {
                    urls.add(planPPlan.getRoute());
                }
                QueryWrapper<PlanPCondition> planPConditionQueryWrapper = new QueryWrapper<>();
                planPConditionQueryWrapper.eq("plan_id", planPPlan.getId());
                planPConditionService.remove(planPConditionQueryWrapper);

                //删除村庄信息
                QueryWrapper<PlanPFbase> planPFbaseQueryWrapper = new QueryWrapper<>();
                planPFbaseQueryWrapper.eq("plan_id", planPPlan.getId());
                planPFbaseService.remove(planPFbaseQueryWrapper);

                /*//删除仓库信息
                QueryWrapper<PlanPDepot> planPDepotQueryWrapper = new QueryWrapper<>();
                planPDepotQueryWrapper.eq("plan_id", planPPlan.getId());
                List<PlanPDepot> planPDepots = planPDepotService.list(planPDepotQueryWrapper);
                planPDepotService.remove(planPDepotQueryWrapper);

                //删除物资信息
                for (PlanPDepot planPDepot : planPDepots) {
                    QueryWrapper<PlanPDtml> planPDtmlQueryWrapper = new QueryWrapper<>();
                    planPDtmlQueryWrapper.eq("plan_id", planPDepot.getId());
                    planPDtmlService.remove(planPDtmlQueryWrapper);
                }*/

            }

            for (String planUrl : urls) {
                if (planUrl != null) {
                    if (minioOrOss) {
                        fileOssStorageService.delete(planUrl);
                    } else {
                        URL url = new URL(planUrl);
                        String path = url.getPath();
                        path = minIOConfigProperties.getEndpoint() + path;
                        fileStorageService.delete(path);
                    }
                }
            }
        }

    }

    @Override
    public AjaxResult getDepot(String id) {
        //根据仓库id查询仓库和物资信息
        try {
            //查询村镇基础信息
            QueryWrapper<PlanPDepot> planPDepotQueryWrapper = new QueryWrapper<>();
            planPDepotQueryWrapper.eq("id", id);
            PlanPDepot planPDepot = planPDepotService.getOne(planPDepotQueryWrapper);

            QueryWrapper<PlanPDtml> planPDtmlQueryWrapper = new QueryWrapper<>();
            planPDtmlQueryWrapper.eq("plan_id", planPDepot.getId());
            List<PlanPDtml> planPDtmls = planPDtmlService.list(planPDtmlQueryWrapper);
            LinkedHashMap<String, Object> result = new LinkedHashMap<>();
            result.put("planPDepot", planPDepot);
            result.put("planPDtmls", planPDtmls);
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("数据查询失败!");
        }
    }

    @Override
    public void edit(List<PlanPDepotDto> planPDepotDtoS) {
        for (PlanPDepotDto planPDepotDto : planPDepotDtoS) {
            PlanPDepot planPDepot = new PlanPDepot();
            BeanUtil.copyProperties(planPDepotDto,planPDepot);
            if (planPDepotDto.getMunit() != null) {
                planPDepot.setMUnit(planPDepotDto.getMunit());
            }
            planPDepotService.updatePlanPDepot(planPDepot);

            List<PlanPDtmlDto> planPDtmlDtos = planPDepotDto.getPlanPDtmlDtos();
            for (PlanPDtmlDto planPDtmlDto : planPDtmlDtos) {
                if (planPDtmlDto.getId() != null) {
                    PlanPDtml planPDtml = new PlanPDtml();
                    BeanUtil.copyProperties(planPDtmlDto, planPDtml);
                    planPDtml.setDepotName(planPDepot.getDepotName());
                    planPDtmlService.updatePlanPDtml(planPDtml);
                }else {
                    PlanPDtml planPDtml = new PlanPDtml();
                    BeanUtil.copyProperties(planPDtmlDto, planPDtml);
                    planPDtml.setId(IdUtils.getId());
                    planPDtml.setPlanId(planPDepotDto.getId());
                    planPDtml.setDepotName(planPDepot.getDepotName());
                    planPDtmlService.save(planPDtml);
                }
            }


        }
    }

    @Override
    public void materialedit(List<PlanPDtml> planPDtmls) {
        for (PlanPDtml planPDtml : planPDtmls) {
            planPDtmlService.updatePlanPDtml(planPDtml);
        }
    }

    @Override
    public AjaxResult deletedepot(List<String> ids) {
        try {

            for (String id : ids) {
                planPDepotService.removeById(id);
                QueryWrapper<PlanPDtml> planPDtmlQueryWrapper = new QueryWrapper<>();
                planPDtmlQueryWrapper.eq("plan_id", id);
                planPDtmlService.remove(planPDtmlQueryWrapper);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除失败!");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deletematerial(List<String> ids) {

        try {
            for (String id : ids) {
                planPDtmlService.removeById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除失败!");
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult getListdepot(String rscd) {
        LinkedList<LinkedHashMap<String, Object>> resultmap = null;
        try {
            QueryWrapper<PlanPDepot> planPDepotQueryWrapper = new QueryWrapper<>();
            planPDepotQueryWrapper.eq("rscd", rscd)
                    .orderByAsc("datayear");
            List<PlanPDepot> planPDepots = planPDepotService.list(planPDepotQueryWrapper);

            resultmap = new LinkedList<>();
            for (PlanPDepot planPDepot : planPDepots) {
                LinkedHashMap<String, Object> result = new LinkedHashMap<>();
                QueryWrapper<PlanPDtml> planPDtmlQueryWrapper = new QueryWrapper<>();
                planPDtmlQueryWrapper.select("ml_name","amount","unit").
                        eq("plan_id", planPDepot.getId());
                List<PlanPDtml> planPDtmls = planPDtmlService.list(planPDtmlQueryWrapper);
                result.put("id", planPDepot.getId());
                result.put("depotName", planPDepot.getDepotName());
                result.put("planPDtmls", planPDtmls);
                resultmap.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询失败!");
        }


        return AjaxResult.success(resultmap);
    }
}
